<template>
  <div>
    <!-- 面包屑区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card>
      <el-row>
        <el-button type="primary" @click="addCateDilond">添加分类</el-button>
      </el-row>
      <!-- 表格区域 -->
      <tree-table
        :data="cateList"
        :columns="columns"
        border
        :selection-type="false"
        show-index
        :show-row-hover="false"
        index-text="#"
        :expand-type="false"
        class="tablecard"
      >
        <!-- 是否有效 -->
        <template slot="del" slot-scope="scope">
          <i class="el-icon-error" v-if="scope.row.cat_deleted" style="color:red"></i>
          <i class="el-icon-success" v-else style="color:#67C23A"></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level===0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level===1">二级</el-tag>
          <el-tag type="danger" v-else>三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="editCate(scope.row.cat_id)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="delcate(scope.row.cat_id)"
          >删除</el-button>
        </template>
      </tree-table>
      <!-- 页码 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryList.pagenum"
        :page-sizes="[1, 5, 10, 15]"
        :page-size="queryList.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
      <!-- 添加分类文本框 -->
      <el-dialog
        title="添加分类"
        :visible.sync="addDialogVisible"
        width="50%"
        @close="addCateDialogClosed"
      >
        <el-form :model="addCateForm" :rules="addCateRules" ref="addCateRef" label-width="100px">
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="addCateForm.cat_name"></el-input>
          </el-form-item>
          <el-form-item label="父级分类" prop="cat_pid">
            <el-cascader
              v-model="selectCateId"
              :options="selectCateParent"
              :props="CateProps"
              @change="handleChange"
              clearable
            ></el-cascader>
          </el-form-item>
        </el-form>
        <!-- 文本框底部 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addCateSub">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑分类文本框 -->
      <el-dialog
        title="添加分类"
        :visible.sync="editDialogVisible"
        width="50%"
        @close="editCateDialogClosed"
      >
        <el-form :model="editCateList" ref="editCateRef" label-width="100px" :rules="editCateRules">
          <el-form-item label="分类名称" prop="cat_name">
            <el-input v-model="editCateList.cat_name"></el-input>
          </el-form-item>
        </el-form>
        <!-- 文本框底部 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editCateSub">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 请求数据参数
      queryList: {
        type: 3,
        pagenum: 1,
        pagesize: 1
      },
      total: 0,
      // 商品分类列表数据
      cateList: [],
      // tree-table数据
      columns: [
        {
          label: "分类名称",
          prop: "cat_name"
        },
        {
          label: "是否有效",
          type: "template",
          template: "del"
        },
        {
          label: "排序",
          type: "template",
          template: "order"
        },
        {
          label: "操作",
          type: "template",
          template: "opt"
        }
      ],

      // 添加分类文本框
      addDialogVisible: false,
      // 添加分类数据验证
      addCateRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" }
        ],
        cat_pid: [
          { required: true, message: "请选择父级分类", trigger: "blur" }
        ]
      },
      // 表单绑定数据 提交请求参数
      addCateForm: {
        cat_name: "",
        // 分类父id
        cat_pid: 0,
        // 分类层级
        cat_level: 0
      },
      CateProps: {
        value: "cat_id",
        label: "cat_name",
        children: "children",
        expandTrigger: "hover",
        checkStrictly: true
      },
      // 保存一二级分类列表
      selectCateParent: [],
      // 绑定选中的父级分类的id数组 必须为数组
      selectCateId: [],
      editDialogVisible: false,
      editCateRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" }
        ]
      },
      editCateList: { cat_name: "" },
      // 根据id查询参数返回数据
      getIdCateList: []
    };
  },
  created() {
    this.getCateList();
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get("categories", {
        params: this.queryList
      });
      console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error("获取商品分类列表失败");
      this.cateList = res.data.result;
      this.total = res.data.total;
    },
    // 一页显示条数发生改变时触发
    handleSizeChange(newsize) {
      this.queryList.pagesize = newsize;
      this.getCateList();
    },
    // 页码发生改变时触发
    handleCurrentChange(pagenum) {
      this.queryList.pagenum = pagenum;
      this.getCateList();
    },
    // 点击按钮 显示添加分类文本框
    async addCateDilond() {
      const { data: res } = await this.$http.get("categories", {
        params: { type: 2 }
      });
      console.log(res);
      if (res.meta.status !== 200) return this.$message.error("获取父级失败");
      this.selectCateParent = res.data;
      console.log(this.selectCateParent);

      this.addDialogVisible = true;
    },
    // 级联选择改变时触发
    handleChange() {
      // console.log(this.selectCateId);
      if (this.selectCateId.length > 0) {
        this.addCateForm.cat_pid = this.selectCateId[
          this.selectCateId.length - 1
        ];
        this.addCateForm.cat_level = this.selectCateId.length;
        console.log(this.addCateForm);
        return;
      } else {
        this.addCateForm.cat_pid = 0;
        this.addCateForm.cat_level = 0;
        return;
      }
    },
    // 关闭对话框 重置表单
    addCateDialogClosed() {
      this.$refs.addCateRef.resetFields();
      this.selectCateId = [];
      this.addCateForm.cat_pid = 0;
      this.addCateForm.cat_level = 0;
    },
    // 点击提交按钮发起请求
    addCateSub() {
      this.$refs.addCateRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          "categories",
          this.addCateForm
        );
        console.log(res);
        if (res.meta.status !== 201) return this.$message.error("创建失败");
        this.getCateList();
        this.addDialogVisible = false;
      });
    },
    // 编辑分类
    async editCate(id) {
      const { data: res } = await this.$http.get("categories/" + id);
      if (res.meta.status !== 200) return this.$message.error("获取失败");
      this.getIdCateList = res.data;
      this.editDialogVisible = true;
    },
    // 关闭文本框重置
    editCateDialogClosed() {
      this.$refs.editCateRef.resetFields();
    },
    // 点击确定提交修改
    editCateSub() {
      this.$refs.editCateRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "categories/" + this.getIdCateList.cat_id,
          {
            cat_name: this.editCateList.cat_name
          }
        );
        if (res.meta.status !== 200) return this.$message.error("更新失败");
        this.getCateList();
        this.editDialogVisible = false;
      });
    },
    // 删除分类
    async delcate(id) {
      const a = await this.$confirm(
        "此操作将永久删除该分类, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (a !== "confirm") return;
      const { data: res } = await this.$http.delete("categories/" + id);
      if (res.meta.status !== 200) return ths.$message.error("删除失败");
      this.getCateList();
      this.$message.success("删除成功");
    }
  }
};
</script>
<style lang="less" scoped>
.tablecard {
  margin: 15px 0;
}
.el-cascader {
  width: 100%;
}
</style>

